import { ref, createVNode, render, mergeProps, Component } from 'vue'
import { ElDialog } from 'element-plus'
import { Custom } from 'custom/index'

export default function dialog(component: Component, dialogProps: any = {}, props: any = {}) {
  return new Promise((resolve, reject) => {
    const container = document.createElement('div')

    let vm
    let visible
    const getDialogProps = (p) => {
      visible = ref(true)
      return mergeProps({
        modelValue: visible.value,
        'onUpdate:modelValue': v => visible.value = v,
        onClosed: () => {
          reject(null)
          render(null, container)
        }
      }, p || {})
    }

    const getProps = p => mergeProps({
      onResolve: (e) => {
        resolve(e)
        render(null, container)
      },
      onReject: (e) => {
        reject(e)
        render(null, container)
      }
    }, p || {})
    
    vm = createVNode(ElDialog, getDialogProps(dialogProps), { default: () => createVNode(component, getProps(props)) })
    vm.appContext = Custom.app._context
    render(vm, container)
    document.body.append(container.firstElementChild)
    
  })
}